import { getToken, setToken, removeToken } from "@/utils/auth"
import { login, getUserInfo } from "@/api/user"
const state = {
    token: getToken(), //从缓存中读取初始值
    userInfo: {}
}

const mutations = {
    setToken(state, token) {
        state.token = token
            //同步到缓存
        setToken(token)
    },
    removeToken(state) {
        state.token = null
        removeToken()
    },
    setUserInfo(state, userInfo) {
        state.getUserInfo = userInfo
    }
}

const actions = {
    async login(context, data) {
        const token = await login(data)
        context.commit("setToken", token)
    },
    async getUserInfo() {
        const result = await getUserInfo()
        context.commit('setUserInfo', result)
    },
    logout(context) {
        context.commit('removeToken') //删除token
        context.commit('setUserInfo', null) //设置空对象
    }
}

export default {
    namespaced: true, // 开启命名空间
    state,
    mutations,
    actions
}